import React, { useEffect, useState } from 'react';
import { Form, Input, InputNumber, Select, DatePicker, Button, message } from 'antd';
import moment from 'moment';
import ReceiptService from '../../services/ReceiptService';
const { Option } = Select;

const AddReceipt = ({ onSuccess, isEditMode = false, record = null }) => {
  const [form] = Form.useForm();
  const [loading, setLoading] = useState(false);

  // 票据类型选项
  const receiptTypes = [
    '增值税专用发票',
    '普通发票',
    '电子发票',
    '其他'
  ];

  // 初始化表单值（编辑模式下）
  useEffect(() => {
    if (isEditMode && record) {
      form.setFieldsValue({
        relatedOrder: record.relatedOrder,
        receiptDate: moment(record.receiptDate),
        receiptType: record.receiptType,
        receiptPrice: record.receiptPrice,
        receiptNumber: record.receiptNumber,
        receiptContent: record.receiptContent,
        receiptBelong: record.receiptBelong,
        receiptMiddle: record.receiptMiddle
      });
    } else {
      form.resetFields();
    }
  }, [isEditMode, record, form]);

  const onFinish = async (values) => {
    try {
      setLoading(true);

      // 准备提交数据
      const submitData = {
        ...values,
        receiptDate: values.receiptDate.format('YYYY-MM-DD')
      };

      if (isEditMode) {
        // 编辑模式 - 调用更新接口
        await ReceiptService.updateReceipt(record.id, submitData);
        message.success('票据更新成功');
      } else {
        // 添加模式 - 调用创建接口
        await ReceiptService.createReceipt(submitData);
        message.success('票据添加成功');
      }

      onSuccess(); // 通知父组件操作成功
    } catch (error) {
      message.error(error.response?.data?.message ||
                   (isEditMode ? '更新失败' : '添加失败'));
    } finally {
      setLoading(false);
    }
  };

  return (
    <Form
      form={form}
      layout="vertical"
      onFinish={onFinish}
    >
      <Form.Item
        name="relatedOrder"
        label="关联订单"
        rules={[{ required: true, message: '请输入关联订单' }]}
      >
        <Input placeholder="请输入关联订单号" />
      </Form.Item>

      <Form.Item
        name="receiptNumber"
        label="票据号码"
        rules={[{ required: true, message: '请输入票据号码' }]}
      >
        <Input placeholder="请输入票据号码" />
      </Form.Item>

      <Form.Item
        name="receiptPrice"
        label="票据金额"
        rules={[{ required: true, message: '请输入票据金额' }]}
      >
        <InputNumber
          style={{ width: '100%' }}
          min={0}
          precision={2}
          placeholder="请输入票据金额"
        />
      </Form.Item>

      <Form.Item
        name="receiptType"
        label="票据类型"
        rules={[{ required: true, message: '请选择票据类型' }]}
      >
        <Select placeholder="请选择票据类型">
          {receiptTypes.map(type => (
            <Option key={type} value={type}>{type}</Option>
          ))}
        </Select>
      </Form.Item>

      <Form.Item
        name="receiptDate"
        label="开票日期"
        rules={[{ required: true, message: '请选择开票日期' }]}
      >
        <DatePicker
          style={{ width: '100%' }}
          disabledDate={(current) => current && current > moment().endOf('day')}
        />
      </Form.Item>

      <Form.Item
        name="receiptContent"
        label="票据内容"
        rules={[{ required: true, message: '请输入票据内容' }]}
      >
        <Input.TextArea placeholder="请输入票据内容" rows={3} />
      </Form.Item>

      <Form.Item
        name="receiptBelong"
        label="票据归属"
        rules={[{ required: true, message: '请输入票据归属' }]}
      >
        <Input placeholder="请输入票据归属" />
      </Form.Item>

      <Form.Item
        name="receiptMiddle"
        label="票据中间方"
        rules={[{ required: true, message: '请输入票据中间方' }]}
      >
        <Input placeholder="请输入票据中间方" />
      </Form.Item>

      <Form.Item>
        <Button type="primary" htmlType="submit" loading={loading} block>
          {isEditMode ? '更新' : '提交'}
        </Button>
      </Form.Item>
    </Form>
  );
};

export default AddReceipt;